// 相关文档 https://vuex.vuejs.org/zh/api/#subscribeaction
//https://blog.csdn.net/qq_33551792/article/details/102973184


const NAMESPACE = '@@loading';// 定义模块名

const createLoadingPlugin = ({
                                 namespace = NAMESPACE,
                                 includes = [],
                                 excludes = []
                             } = {}) => {
    return store => {
        if (store.state[namespace]) {
            throw new Error(//                 在当前存储中退出
                `createLoadingPlugin: ${namespace} exited in current store`
            )
        }
        // new vuex的时候注册一个模块进去
        store.registerModule(namespace, {
            namespaced: true,
            state: {
                global: false,// 定义全局loading
                effects: {}
            },
            // 同步方法
            mutations: {
                SHOW(state, {payload}) {
                    state.global = true;
                    state.effects = {
                        ...state.effects,
                        [payload]: true// 将当前的action 置为true
                    }
                },
                HIDE(state, {payload}) {
                    state.global = false;
                    state.effects = {
                        ...state.effects,
                        [payload]: false// 将当前的action 置为false
                    }
                }
            }
        });

        store.subscribeAction({
            // 发起一个action 之前会走这里
            before: action => {
                console.log(`before action ${action.type}`);
                if (shouldEffect(action, includes, excludes)) {
                    store.commit({type: namespace + '/SHOW', payload: action.type})
                }
            },
            // 发起一个action 之后会走这里
            after: action => {
                console.log(`after action ${action.type}`);
                if (shouldEffect(action, includes, excludes)) {
                    store.commit({type: namespace + '/HIDE', payload: action.type})
                }
            }
        })
    }
};
// 判断是否要执行
function shouldEffect({type}, includes, excludes) {
    if (includes.length === 0 && excludes.length === 0) {
        return true
    }

    if (includes.length > 0) {
        return includes.indexOf(type) > -1
    }

    return excludes.length > 0 && excludes.indexOf(type) === -1
}

export default createLoadingPlugin
// 需要在vuex中引入并注册成插件：
/**
 import createLoadingPlugin from 'utils/vuex-loading'
 export default new Vuex.Store({
  plugins: [createLoadingPlugin()],
  state: {
    // loading: false,
    direction: 'forward'
  }
})
 **/
